﻿using RimWorld;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Verse;

namespace Miao.Stand
{
    public class StandMasterHediff : HediffWithComps
    {
        public StandPawn stand;
        public int standInactive;
        //保存
        public override void ExposeData()
        {
            base.ExposeData();
            Scribe_References.Look(ref stand, "standMaster", true);
            Scribe_Values.Look(ref standInactive, "standInactive");
        }

        public override void Notify_PawnPostApplyDamage(DamageInfo dinfo, float totalDamageDealt)
        {
            base.Notify_PawnPostApplyDamage(dinfo, totalDamageDealt);
            //dinfo.Def.Worker.Apply(dinfo, stand);
        }
        public override void Tick()
        {
            base.Tick();

            if (!pawn.IsColonist && Find.TickManager.TicksGame % 250 == 0)
            {
                StandAITick();
            }
        }

        public override IEnumerable<Gizmo> GetGizmos()
        {
            Gizmo standActiveGizmo = StandActiveGizmo(__instance.pawn, standHediff);

        }

        /// <summary>
        /// 简单的替身召唤机制
        /// </summary>
        void StandAITick()
        {
            if (!stand.Spawned)
            {
                if (pawn.mindState.meleeThreat != null)
                {
                    standInactive = 0;
                    stand.ActiveStand(pawn.Position, pawn.Map);
                }
                else if (pawn.mindState.enemyTarget != null)
                {
                    if (pawn.Position.InHorDistOf(pawn.mindState.enemyTarget.Position, stand.standRanage))
                    {
                        standInactive = 0;
                        stand.ActiveStand(pawn.Position, pawn.Map);
                    }
                }
            }
            else
            {
                if (pawn.mindState.meleeThreat == null && pawn.mindState.enemyTarget == null)
                {
                    standInactive++;
                    if (standInactive == 20)
                    {
                        stand.InactiveStand();
                        standInactive = 0;
                    }
                }
                else
                {
                    standInactive = 0;
                }
            }

        }


        public void ActiveStand(IntVec3 position, Map map)
        {
            stand.ActiveStand(position, map);
            //RCellFinder.RandomWanderDestFor(stand.owner, stand.owner.Position, stand.radius, null, Danger.None);
            //Thing data =  GenSpawn.Spawn(stand, position, map);
        }
        public void InactiveStand()
        {
            stand.InactiveStand();
        }
    }
}
